﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;


namespace GaleSong
{
    public class Attacher
    {
        #region IsCurrentOwnerWindow

        /// <summary>
        ///     IsCurrentOwnerWindow Attached Dependency Property
        /// </summary>
        public static readonly DependencyProperty IsCurrentOwnerWindowProperty =
            DependencyProperty.RegisterAttached("IsCurrentOwnerWindow", typeof(bool), typeof(Attacher),
                new FrameworkPropertyMetadata(false,
                    OnIsCurrentOwnerWindowChanged));

        /// <summary>
        ///     Gets the IsCurrentOwnerWindow property.  This dependency property
        ///     indicates whether close the window.
        /// </summary>
        public static bool GetIsCurrentOwnerWindow(DependencyObject d)
        {
            return (bool)d.GetValue(IsCurrentOwnerWindowProperty);
        }

        /// <summary>
        ///     Sets the IsCurrentOwnerWindow property.  This dependency property
        ///     indicates whether close the window.
        /// </summary>
        public static void SetIsCurrentOwnerWindow(DependencyObject d, bool value)
        {
            d.SetValue(IsCurrentOwnerWindowProperty, value);
        }

        /// <summary>
        ///     Handles changes to the IsCurrentOwnerWindow property.
        /// </summary>
        private static void OnIsCurrentOwnerWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if(UICommon.IsInDesignMode)
            {
                return;
            }

            var window = d as Window;
            if(window == null)
            {
                throw new ArgumentException(
                    string.Format(
                        "The attached property IsCurrentOwnerWindow can only affect on window. Current Type {0}",
                        d.GetType()));
            }

            if((bool)e.NewValue && !(bool)e.OldValue)
            {
                if(Keyboard.FocusedElement != null)
                {
                    Window currentWindow = Window.GetWindow(Keyboard.FocusedElement as DependencyObject);
                    window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    window.Owner = currentWindow;
                }
                else if (Application.Current != null && Application.Current.MainWindow != null && Application.Current.MainWindow != window)
                {
                    window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    window.Owner = Application.Current.MainWindow;
                }
            }
        }

        #endregion
    }
}